package com.ktjy.crm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.crm.entity.Role;
import com.ktjy.crm.entity.User;
import com.ktjy.crm.service.IRoleService;
import com.ktjy.crm.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/dologin")
    public String dologin(String usrName, String usrPassword, HttpServletRequest request) {
        User user = userService.login(usrName, usrPassword);
        if (user != null) {
            request.getSession().setAttribute("loginUser", user);
            return "main";
        }else {
            request.setAttribute("message", "登录失败，用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "login";
    }

//    @GetMapping(value = "/user/list")
//    public String findUsers(String usrName, Long roleId, Model model) {
//        HashMap<String, Object> hashMap = new HashMap<>();
//        hashMap.put("usrName", usrName);
//        hashMap.put("roleId", roleId);
//        IPage<User> list = userService.getUserByPage(hashMap);
//        model.addAttribute("users", list);
//        return "user/list";
//    }
// 分页查询用户信息
    @RequestMapping(value = "/user/list")
    public String list(Model model, String usrName,
                       @RequestParam(required = false, defaultValue = "0") Long roleId,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("usrName", usrName);
        hashMap.put("roleId", roleId);
        hashMap.put("pageIndex", pageIndex);
        hashMap.put("pageSize", 3);
        IPage<User> userPager = userService.getUserByPage(hashMap);
        model.addAttribute("userPager", userPager);
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        //查询所有角色
//        List<Role> roles = roleService.findAllRoles();
//        model.addAttribute("roles", roles);
        return "user/list";
    }
}
